package com.acme.bankapp.service.email;

import com.acme.bankapp.domain.bank.client.email.Email;
import com.acme.bankapp.service.email.exception.AddAfterCloseQueueException;
import com.acme.bankapp.service.email.exception.GetAfterCloseQueueException;

public class EmailService implements Runnable {
	private static volatile EmailService instance = null;

	private EmailService() {
		queue = new Queue<Email>(10);
		/*
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					while (true) {
						sendEmail(queue.get());
					}
				} catch (GetAfterCloseQueueException exception) {
					System.out.println("Error when get from queue");
				}

			}}).start();
			*/
		new Thread(this).start();
	}

	public static EmailService getEmailService() {
		if (instance == null) {
			synchronized (EmailService.class) {
				if (instance == null) {
					instance = new EmailService();
				}
			}
		}
		return instance;
	}

	@Override
	public void run() {
		try {
			while (true) {
				sendEmail(queue.get());
			}
		} catch (GetAfterCloseQueueException exception) {
				System.out.println("Done work EmailService");
		}
	}

	public void sendNotificationEmail(Email email) {
		try {
			if (!queue.isClosing()) {
				queue.add(email);
			}
		} catch (AddAfterCloseQueueException exception) {
			System.out.println("Error when add to queue");
		}
	}

	private Queue<Email> queue;

	public void close() {
		queue.close();
	}


	private void sendEmail(Email email) {
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
		}
		System.out.println("Send email for client: " + email.getClient() + " to email: " + email.getEmailAddress() + ".");
	}
}
